package com.wusuowei.springboot.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wusuowei.springboot.model.dto.UserDTO;
import com.wusuowei.springboot.model.dto.UserPasswordDTO;
import com.wusuowei.springboot.model.po.User;
import com.wusuowei.springboot.model.po.UserRole;
import com.wusuowei.springboot.service.UserRoleService;
import com.wusuowei.springboot.service.UserService;
import com.wusuowei.springboot.utils.R;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lgy
 */
@Slf4j
@RestController
@Api(value = "管理接口", tags = "用户管理接口")
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private UserRoleService userRoleService;

    // 用户登录
    @PostMapping("/login")
    public R login(@RequestBody UserDTO user) {
        // 新增或者更新
        UserDTO userDTO = userService.login(user);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", userDTO.getToken());
        map.put("user", userDTO);
        map.put("menus", userDTO.getMenus());
        return R.ok().setData(map);
    }


    @PostMapping("/register")
    public R register(@RequestBody UserDTO user) {
        // 新增或者更新
        userService.register(user);
        return R.ok();
    }

    /**
     * @description 根据用户名返回用户
     * @param username 用户名
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:09
     */
    @GetMapping("/username/{username}")
    public R getByUsername(@PathVariable String username) {
        User one = userService.getByName(username);
        return R.ok().setData(one);
    }


    /**
     * @description 检查用户名
     * @param username 用户名
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:09
     */
    @GetMapping("/check")
    public R countByUsername(@RequestParam String username) {
        long count = userService.count(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (count != 0) {
            return R.error("用户名已存在");
        }
        return R.ok();
    }

    /**
     * @description 新增和修改
     * @param user 使用者
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:10
     */
    @PostMapping
    public R save(@RequestBody User user) {
        // 新增或者更新
        userService.saveOrUpdate(user);
        UserRole userRole = new UserRole();

        userRole.setUserId(user.getId());
        userRole.setRoleId(Long.valueOf(user.getRole()));
        //把原来的关系删了
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId,userRole.getUserId()));
        //在进行添加
        userRoleService.save(userRole);

        return R.ok();
    }


    /**
     * @description 查询所有用户
     *
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:10
     */
    @GetMapping
    public R findAll() {
        List<User> all = userService.list();
        return R.ok().setData(all);
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        userService.removeById(id);
        return R.ok();
    }

    /**
     * @description 批量删除
     * @param ids
     * @return {@link R }
     * @author LGY
     * @date 2023/03/24 21:10
     */
    @PostMapping("/del/batch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        userService.removeBatchByIds(ids);
        return R.ok();
    }

    /**
     * @description 查找页面
     * @param pageNum 书籍页码
     * @param pageSize 页面大小
     * @param username 用户名
     * @param email 电子邮件
     * @param address 住址
     * @return {@link Map }<{@link String }, {@link Object }>
     * @author LGY
     * @date 2023/03/24 21:11
     */
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(required = false) String username,
                                        @RequestParam(required = false) String email,
                                        @RequestParam(required = false) String address) {

//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        if (!"".equals(username)) {
//            queryWrapper.like("username", username);
//        }
//        if (!"".equals(email)) {
//            queryWrapper.like("email", email);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address", address);
//        }
//        queryWrapper.orderByAsc("id");
//
//        Page<User> page = userService.page(new Page<User>(pageNum, pageSize),queryWrapper);
//        long total = page.getTotal();
//        Map<String, Object> res = new HashMap<>();
//        res.put("data", page.getRecords());
//        res.put("total", total);
        Page<User> page = userService.findPage(new Page<>(pageNum, pageSize), username, email, address);
        return R.ok().setData(page);
    }

    @PostMapping("/password")
    public R password(@RequestBody UserPasswordDTO userPasswordDTO) {
        userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword()));
        userPasswordDTO.setNewPassword(SecureUtil.md5(userPasswordDTO.getNewPassword()));
        try {
            userService.updatePassword(userPasswordDTO);
        } catch (Exception e) {
            return R.error("原密码错误");
        }
        return R.ok();
    }
}
